var plugin = requirePlugin("WechatSI");
var manager;

var startVoice = function ( callback) {
  manager = plugin.getRecordRecognitionManager();
  manager.onRecognize = function (res) {
    console.log("current result", res.result)
  }
  manager.onStop = function (res) {
    console.log("record file path", res.tempFilePath)
    console.log("result", res.result);
    if (callback) callback(true, res.result, res.tempFilePath);
  }
  manager.onStart = function (res) {
    console.log("成功开始录音识别", res)    
  }
  manager.onError = function (res) {
    console.error("error msg", res.msg);
    if(callback) callback(false,res.code+":"+res.msg);
  } 

  manager.start();
}; 

var stopVoice = function (callback) {
  manager.stop();
  if (callback){
    callback();
  }
};


var chnNumChar = {
  '零': 0,
  '一': 1,
  '二': 2,
  '三': 3,
  '四': 4,
  '五': 5,
  '六': 6,
  '七': 7,
  '八': 8,
  '九': 9
};
var chnNameValue = {
  '十': { value: 10, secUnit: false },
  '百': { value: 100, secUnit: false },
  '千': { value: 1000, secUnit: false },
  '万': { value: 10000, secUnit: true },
  '亿': { value: 100000000, secUnit: true }
}
var chi = '0123456789一二三四五六七八九十百千万亿';
var ali = '0123456789';
function ChineseToNumber(chnStr) {
  if (chnStr.indexOf('十')==0){
    chnStr = "一" + chnStr;
  }

  var rtn = 0;
  var section = 0;
  var number = 0;
  var secUnit = false;
  var str = chnStr.split('');

  for (var i = 0; i < str.length; i++) {
    var num = chnNumChar[str[i]];
    if (typeof num !== 'undefined') {
      number = num;
      if (i === str.length - 1) {
        section += number;
      }
    } else {
      if (!chnNameValue[str[i]]){
        return 0;
      }
      var unit = chnNameValue[str[i]].value;
      secUnit = chnNameValue[str[i]].secUnit;
      if (secUnit) {
        section = (section + number) * unit;
        rtn += section;
        section = 0;
      } else {
        section += (number * unit);
      }
      number = 0;
    }
  }
  return rtn + section;
} 
function textToNum(str) {
  str=str.replace('两','二');
  var arr = str.split("");
  var chnum = '';
  for (var i = 0; i < arr.length; i++) {
    if (chi.indexOf(arr[i]) >= 0) { 
      chnum += arr[i];
    }
  }
  if (chnum!=''){
    if (ali.indexOf(chnum)>=0){
      return chnum;
    }else{
      if (!isNaN(chnum)){
        return Number(chnum);
      }else{
        return ChineseToNumber(chnum);
      }      
    }    
  }else{
    return 0;
  }
  
}
module.exports = {
  textToNum: textToNum,
  startVoice: startVoice,
  stopVoice:stopVoice,
  ChineseToNumber:ChineseToNumber
}